package com.yanqu.road.server.manger.maidian.resource;

import com.yanqu.data.analytics.constant.EventDataConstants;
import com.yanqu.data.analytics.helper.DataBuilder;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.player.UserBagItem;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.manger.DataAnalyticsMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.maidian.DefaultEventTraceAction;
import com.yanqu.road.server.manger.maidian.entity.BuyShopItem;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class BuyItemLog {

    //道具购买  缓存
    public static Map<Long, List<Map<String, Object>>> buyItemMap = new ConcurrentHashMap<>();

    public static void logoutUploadShopBuyItem(GamePlayer player){

        List<Map<String, Object>> list = DataAnalyticsMgr.popUserMapData(player.getUserId(), buyItemMap);

        if(list == null || list.size() == 0){
            return;
        }

        trackShopBuyItem(player, list);

    }

    /**
     * 商店模块 购买道具
     */
    public static void trackShopBuyItem(GamePlayer player, MallInfo mallInfo, long count, Property consume, Property rewards) {
        try{
            if (!DataAnalyticsMgr.openDataAnalytics()) return;

            if(consume == null || rewards == null){
                return;
            }
            List<Map<String, Object>> list;
            list = DataAnalyticsMgr.getUserMapDataForNew(player.getUserId(), buyItemMap);

            synchronized (list){
                try {
                    Map<String, Object> map = new HashMap<>();
                    map.put(EventDataConstants.Shop.STORE_TYPE, mallInfo.getShopType());
                    String[] reward = mallInfo.getReward().split("=");
                    String[] price = mallInfo.getPrice().split("=");
                    map.put(EventDataConstants.Shop.ITEM_ID, reward[0]); //获得的道具
                    map.put(EventDataConstants.Shop.ITEM_PRICE, Integer.valueOf(price[1])); //消耗的道具的单价
                    //map.put(EventDataConstants.Shop.COST_TYPE, price[0]); //消耗的道具
                    map.put(EventDataConstants.Shop.COST_NUM, consume.getCountByGoodsId(Integer.valueOf(price[0])).intValue());
                    map.put(EventDataConstants.Shop.ITEM_NUM, rewards.getCountByGoodsId(Integer.valueOf(reward[0])).intValue());
                    list.add(map);
                }catch (Exception e){
                    DataAnalyticsMgr.getLogger().error("商品模块 购买道具 mailId:" + mallInfo.getMallId(), e);
                }

                if(list.size() + 1 >= EventDataConstants.ARRAY_OBJECT_MAX_SIZE){
                    trackShopBuyItem(player, list);
                }
            }

        }catch (Exception e){
            DataAnalyticsMgr.getLogger().error("写入TA平台数据异常。商品模块 购买道具", e);
        }
    }

    private static void trackShopBuyItem(GamePlayer player, List<Map<String, Object>> list) {
        try{
            DefaultEventTraceAction traceAction = new DefaultEventTraceAction(EventDataConstants.Shop.BUY_ITEM, player);
            traceAction.build(EventDataConstants.Shop.ITEM_INFO, list).trace();
        }catch (Exception e){
            DataAnalyticsMgr.getLogger().error(" trackShopBuyItem ", e);
        }
    }

    /**
     * 单次上报玩家购买情况
     * @param player 玩家
     * @param buyShopItem 购买项
     */
    public static void trackShopBuyItemSingle(GamePlayer player, BuyShopItem buyShopItem) {
        try {
            if (!DataAnalyticsMgr.openDataAnalytics()) return;

            DefaultEventTraceAction traceAction = new DefaultEventTraceAction(EventDataConstants.Shop.BUY_ITEM, player);
            traceAction.build(EventDataConstants.Shop.STORE_TYPE, buyShopItem.getMallInfo().getShopType());
            traceAction.build(EventDataConstants.Shop.STORE_ACTTYPE, buyShopItem.getMallInfo().getActivityType());
            traceAction.build(EventDataConstants.Shop.PAY_REASON_ID, buyShopItem.getMallInfo().getMallId());
            List<Integer> priceList = StringUtils.stringToIntegerList(buyShopItem.getMallInfo().getPrice(), "=");
            if(priceList.size() == 2) {
                traceAction.build(EventDataConstants.Shop.ITEM_ID, priceList.get(0));
                traceAction.build(EventDataConstants.Shop.ITEM_PRICE, priceList.get(1));
            }
            traceAction.build(EventDataConstants.Shop.ITEM_GET, PropertyHelper.parsePropertyToString(buyShopItem.getReward()));
            traceAction.build(EventDataConstants.Shop.BUY_NUM, buyShopItem.getCount());
            traceAction.trace();
        }catch (Exception e){
            DataAnalyticsMgr.getLogger().error("error :", e);
        }
    }

    /**
     * 单次上报玩家购买情况(活动)
     * @param player 玩家
     * @param buyShopItem 购买项
     */
    public static void trackActivityShopBuyItemSingle(GamePlayer player, BuyShopItem buyShopItem) {
        try {
            if (!DataAnalyticsMgr.openDataAnalytics()) return;

            DefaultEventTraceAction traceAction = new DefaultEventTraceAction("actbuy_item", player);
            traceAction.build("actbuy_id", buyShopItem.getMallInfo().getMallId());
            traceAction.build(EventDataConstants.Shop.BUY_NUM, buyShopItem.getCount());
            String priceStr = MallRechargeConfigMgr.getPriceStr(buyShopItem.getMallInfo());
            traceAction.build("actbuy_price", priceStr);
            traceAction.build(EventDataConstants.Shop.ITEM_GET, PropertyHelper.parsePropertyToString(buyShopItem.getReward()));
            traceAction.build("type", buyShopItem.getMallInfo().getActivityType());
            traceAction.build("actbuy_markid", buyShopItem.getMallInfo().getMallMarkId());
            traceAction.build("store_type", buyShopItem.getMallInfo().getShopType());
            traceAction.trace();
        }catch (Exception e){
            DataAnalyticsMgr.getLogger().error("error :", e);
        }
    }

    /**
     * 礼包埋点
     */
    public static void trackTriggerEject(GamePlayer player, int conditionId, MallInfo mallInfo){
        try {
            if (!DataAnalyticsMgr.openDataAnalytics()) return;

            DefaultEventTraceAction traceAction = new DefaultEventTraceAction("trigger_eject", player);
            traceAction.build("trigger_id", conditionId);
            traceAction.build("trigger_type", mallInfo.getShopType());
            traceAction.build("trigger_mallid", mallInfo.getMallId());
            traceAction.build("trigger_markid", mallInfo.getMallMarkId());
            traceAction.trace();
        }catch (Exception e){
            DataAnalyticsMgr.getLogger().error("error :", e);
        }
    }

    /**
     * 玩家背包每日快照
     */
    public static void trackUserBagSnapshot(GamePlayer player) {
        try {
            if (!DataAnalyticsMgr.openDataAnalytics()) return;

            Map<Integer, UserBagItem> userBagItemMap;
            //公共事件属性
            DataBuilder common = DataBuilder.newBuilder(player.getUserId(), DataAnalyticsMgr.getDistinctId(player.getUserInfo()));
            DataAnalyticsMgr.buildPublicEventData(player, common);
            userBagItemMap = player.getModule(BagModule.class).getUserBagItemMap();
            UserInfo userInfo = player.getUserInfo();

            //对象组，最大500
            List<Map<String, Object>> objectArr = new ArrayList<>();
            for (UserBagItem value : userBagItemMap.values()) {
                if(value.getNum() <= 0){
                    continue;
                }
                Map<String, Object> val = new HashMap<>();
                val.put(EventDataConstants.Shop.COST_ID, value.getGoodsId());
                val.put(EventDataConstants.Shop.COST_NOWVALUE, value.getNum());
                objectArr.add(val);
                if(objectArr.size() >= EventDataConstants.ARRAY_OBJECT_MAX_SIZE){
                    DataBuilder dataBuilder = DataBuilder.newBuilder(userInfo.getUserId(), DataAnalyticsMgr.getDistinctId(userInfo));
                    dataBuilder.build(EventDataConstants.Shop.COST_NOWNUM, objectArr);
                    dataBuilder.getDataMap().putAll(common.getDataMap());
                    DataAnalyticsMgr.provider.track(dataBuilder.getAccountId(), dataBuilder.getDistinctId(), EventDataConstants.Shop.COST_NOW, dataBuilder.getDataMap());
                    objectArr = new ArrayList<>();
                }
            }
            if(objectArr.size() > 0){
                DataBuilder dataBuilder = DataBuilder.newBuilder(userInfo.getUserId(), DataAnalyticsMgr.getDistinctId(userInfo));
                dataBuilder.build(EventDataConstants.Shop.COST_NOWNUM, objectArr);
                dataBuilder.getDataMap().putAll(common.getDataMap());
                DataAnalyticsMgr.provider.track(dataBuilder.getAccountId(), dataBuilder.getDistinctId(), EventDataConstants.Shop.COST_NOW, dataBuilder.getDataMap());
            }
        }catch (Exception e){
            DataAnalyticsMgr.getLogger().error("error :", e);
        }


    }
}
